package com.george.es.book.controller.api.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.george.es.book.pojo.entity.Book;
import com.george.es.book.pojo.entity.EsEntity;
import com.george.es.book.pojo.entity.UserEntity;
import com.george.es.book.util.EsUtil;
import com.george.es.entity.Result;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户数据接口获取
 * </p>
 *
 * @author GeorgeChan 2019/9/5 9:35
 * @version 1.0
 * @since jdk1.8
 */
@RestController
@RequestMapping("/api/user")
public class UserApiController {
    private final Logger logger = LoggerFactory.getLogger(UserApiController.class);

    @Autowired
    private EsUtil esUtil;

    /**
     * 用户列表
     * @param page 页码
     * @param limit 每页条数
     * @return 数据集合
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result userList(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                           @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                           @RequestParam(value = "username", required = false, defaultValue = "") String username) {
        List<Map<String, Object>> result = new ArrayList<>();
        long total = 0;

        SearchRequest searchRequest = new SearchRequest("user_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(QueryBuilders.matchQuery("username", "George"));
        if (StringUtils.isNotEmpty(username)) {
            searchSourceBuilder.query(QueryBuilders.matchQuery("username", username));
        } else {
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        }
        searchSourceBuilder.from((page - 1)*limit);
        searchSourceBuilder.size(limit);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));
        searchRequest.source(searchSourceBuilder);

        try {
            SearchResponse response = EsUtil.client.search(searchRequest, RequestOptions.DEFAULT);
            total = response.getHits().getTotalHits().value;
            logger.info(JSON.toJSONString(response));
            for (SearchHit hit : response.getHits().getHits()) {
                Map<String, Object> map = hit.getSourceAsMap();
                result.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(true, 0, "查询成功！", result, total);
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public Result edit(@RequestParam(value = "params", required = false, defaultValue = "") String params) {
        UserEntity userEntity = JSON.parseObject(params, UserEntity.class);
        EsEntity<UserEntity> entity = new EsEntity<>(userEntity.getId().toString(), userEntity);
        esUtil.insertOrUpdateOne(EsUtil.USER_INDEX_NAME, entity);
        return new Result(true, 0, "操作成功！");
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Result delete(@PathVariable(value = "id", required = true)long id) {
        List<Long> list = Lists.newArrayList();
        list.add(id);
        esUtil.deleteBatch(EsUtil.USER_INDEX_NAME, list);
        return new Result(true, 0, "操作成功！");
    }

    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(@RequestParam(value = "ids", required = true)String ids) {
        List<Long> list = Lists.newArrayList();
        ids = StringUtils.replace(ids, StringPool.LEFT_SQ_BRACKET,StringPool.EMPTY);
        ids = StringUtils.replace(ids, StringPool.RIGHT_SQ_BRACKET,StringPool.EMPTY);
        List<String> idList = Arrays.asList(StringUtils.split(ids, StringPool.COMMA));
        for (String id : idList) {
            list.add(Long.valueOf(id));
        }
        esUtil.deleteBatch(EsUtil.USER_INDEX_NAME, list);
        return new Result(true, 0, "操作成功！");
    }
}
